package com.ccsoft.backuptools.utils;

import com.ccsoft.backuptools.dao.CallProcedureMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
public class DbUtils {
    @Autowired
    private CallProcedureMapper dao;
    @Value("${app.backup-dbname}")
    private String dbNames;
    @Value("${app.backup-folder}")
    private String backupFolder;

    public void backupdb(String dbName){
        String filePath = getBackupFilename(dbName);
        System.out.println("开始备份数据库" + new Date().toString());
        dao.backupdb(dbName, filePath);
        System.out.println("备份结束" + new Date().toString());
    }

    public void backupdbs(){
        if(dbNames == null || dbNames.length()<=0) return;

        String[] dbs = dbNames.split(",");
        for (int i = 0; i < dbs.length; i++) {
            String dbName = Optional.ofNullable(dbs[i]).orElse("").trim();
            if(dbName.length()<=0) continue;
            backupdb(dbName);
        }
    }

    private String getBackupFilename(String dbName){
        if(dbName == null || dbName.length()<=0) return "";
        String dateString = DatetimeUtils.formatDate(new Date(),"yyyyMMddHHmmss");
        return backupFolder + "\\" + dbName + dateString + ".bak";
    }
}
